import os
import re
from string import whitespace

'''
文件重命名
'''


def renamefile(url, old_str, new_str, last_code):
    old_str_split = old_str.split("&&")
    for dirpath, dirnames, filenames, in os.walk(url):
        for filename in filenames:
            try:
                # if not filename.__contains__(last_code):
                #     continue
                inputfilename = os.path.join(dirpath, filename)
                new_filename = filename
                for str in old_str_split:
                    new_filename = new_filename.replace(str, new_str)
                outfilename = os.path.join(dirpath, new_filename)
                os.rename(inputfilename, outfilename)
                print("old_name:{}-->new_name:{}".format(inputfilename, outfilename))
            except FileExistsError as f:
                print(f)
                continue

def rename(file_path):
    for dirpath, dirnames, filenames in os.walk(file_path):
        for filename in filenames:
            try:
                inputfilename = dirpath.replace("\\", "/") + '/' + filename
                tables = str.maketrans('', '', "()【】-  */" + r"""!"#$%&'()*+，,-/:;<=>?@[\]^_`{|}~™""" + whitespace)
                # 去除中文
                pattern = re.compile(u"[\u4e00-\u9fa5]+")
                filename = re.sub(pattern, "", filename)
                outfilename = dirpath.replace("\\", "/") + '/' + str.strip(filename.translate(tables))
                print('inputfilename:' + inputfilename)
                print('outfilename:' + outfilename)
                if not inputfilename.__eq__(outfilename) and os.path.exists(outfilename):
                     os.remove(outfilename)
                os.rename(inputfilename, outfilename)
            except FileExistsError as f:
                print(f)
                continue

if __name__ == '__main__':
    url = r'D:\22'
    old_str = r"《&&: && &&。&&，&& &&!&&》&&#&&\&&&;&&[&&]&&♥&&－&&?&&？&&【&&】&&+&&⁉️&&～&&〖&&〗&&『&&』&&/&&-&&！&& &&の&&guochan2048.com&&(&&)&&（&&）&&，&&,&&gc2048.com&&“&&”&&：" \
              r"&&上传&&HD&&增强&&版&&高清&&hongyanyixiao&&18bt.net&&推荐&&粉丝群&&史上&&mfgc&&.com&&制片厂&&d6p6.com&&传媒&&tsbt" \
              r"&&劲爆&&无水印&&sf&&bt&&th&&大尺度&&情趣&&gc&&2048&&.com&&jav20s8&&⋯&&完美&&極品&&蘿莉&&美少女&&死水庫&&制服&&私拍&&tsbt9" \
              r"&&avav55&&@&&avav66&&.xyz&&4K&&4k&&原画&&jav20s8&&原创&&SEX8.CC&&活动&&▌&&avav&&aavv&&天花板&&出品&&77&&36&&／&&、&&✿&&kc&&の&&最新&&SD&&SWAG&&.tv&&club&&...&&™"
    # old_str = r" "
    new_str = ""
    last_code = ".mp4"
    renamefile(url, old_str, new_str, last_code)
    # rename(url)
